# -*- coding: utf-8 -*-

from django import forms

def isUnique(form, field, data):
    """Validates that a value is unique for a field.
    """
    if not isinstance(form, forms.ModelForm):
        raise TypeError, u'The instance passed to isUnique is not a subclass of djangoforms.ModelForm'

    model = form._meta.model
    matching_obj = model.gql("WHERE " + str(field) + " = :1", data).get()
    if not matching_obj:
        return data

    if form.instance and form.instance.key() == matching_obj.key():
        return data
    
    raise forms.ValidationError('%(fieldname)s já cadastrado. Escolha outro.' % {'fieldname':field.capitalize()})
